package com.kj.xuyuan.mine;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.kj.xuyuan.R;
import com.kj.xuyuan.base.BaseActivity;
import com.kj.xuyuan.base.BaseModel;
import com.kj.xuyuan.base.Constants;
import com.kj.xuyuan.http.JsonCallback;
import com.kj.xuyuan.http.OkGoUtil;
import com.kj.xuyuan.http.UrlConstants;
import com.kj.xuyuan.model.EditDataBean;
import com.kj.xuyuan.model.JsonBean;
import com.kj.xuyuan.model.MakeFriendConditionBean;
import com.kj.xuyuan.model.UserInfoBean;
import com.kj.xuyuan.pop.SelectFriendAddressPopWindow;
import com.kj.xuyuan.util.GetJsonDataUtil;
import com.kj.xuyuan.util.JSONUtils;
import com.kj.xuyuan.util.LogUtils;
import com.kj.xuyuan.util.SPUtils;
import com.kj.xuyuan.util.StringUtils;
import com.kj.xuyuan.util.ToastUtil;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 征友条件
 */
public class MakeFriendRequestActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.ll_city)
    LinearLayout llCity;
    @BindView(R.id.tv_hometown)
    TextView tvHometown;
    @BindView(R.id.ll_hometown)
    LinearLayout llHometown;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.ll_age)
    LinearLayout llAge;
    @BindView(R.id.tv_height)
    TextView tvHeight;
    @BindView(R.id.ll_height)
    LinearLayout llHeight;
    @BindView(R.id.tv_weight)
    TextView tvWeight;
    @BindView(R.id.ll_weight)
    LinearLayout llWeight;
    @BindView(R.id.tv_education)
    TextView tvEducation;
    @BindView(R.id.ll_education)
    LinearLayout llEducation;
    @BindView(R.id.tv_income)
    TextView tvIncome;
    @BindView(R.id.ll_income)
    LinearLayout llIncome;
    @BindView(R.id.tv_marry_type)
    TextView tvMarryType;
    @BindView(R.id.ll_marry_type)
    LinearLayout llMarryType;
    @BindView(R.id.tv_when_want_marry)
    TextView tvWhenWantMarry;
    @BindView(R.id.ll_when_want_marry)
    LinearLayout llWhenWantMarry;
    @BindView(R.id.tv_buy_house)
    TextView tvBuyHouse;
    @BindView(R.id.ll_buy_house)
    LinearLayout llBuyHouse;
    @BindView(R.id.tv_buy_car)
    TextView tvBuyCar;
    @BindView(R.id.ll_buy_car)
    LinearLayout llBuyCar;
    @BindView(R.id.tv_smoke)
    TextView tvSmoke;
    @BindView(R.id.ll_smoke)
    LinearLayout llSmoke;
    @BindView(R.id.tv_drink)
    TextView tvDrink;
    @BindView(R.id.ll_drink)
    LinearLayout llDrink;

    private List<EditDataBean> editData;
    private int edit;
    private OptionsPickerView oneListPickerView;
    private String education;
    private String marryTime;
    private String married;
    private String income_start;
    private String income_end;
    private String buyCar;
    private String buyHouse;
    private String height;
    private String weight;
    private String tags;
    private int addressType;//1所在城市  2家乡
    private List<String> ageList;
    private String years;
    private String smoke;
    private String dring;
    private List<JsonBean> mOptions1Items = new ArrayList<>();//添加省份数据
    private ArrayList<ArrayList<String>> mOptions2Items = new ArrayList<>();//添加城市数据
    private ArrayList<ArrayList<ArrayList<String>>> mOptions3Items = new ArrayList<>();//添加地区数据
    private String locationProvince;
    private String locationCity;
    private String province;
    private String city;

    public static void actionStar(Context context){
        Intent intent = new Intent(context,MakeFriendRequestActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_make_friend_requset;
    }

    @Override
    protected void initView() {
        getData();
        initChinaData();
        initEditData();
        initOneList();
        initAgeList();
    }


    private void initChinaData() {
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        mOptions1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                /*if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }*/
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }
            /**
             * 添加城市数据
             */
            mOptions2Items.add(cityList);
            /**
             * 添加地区数据
             */
            mOptions3Items.add(province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    private void initAgeList() {
        ageList = new ArrayList<>();
        for(int i = 18;i<=70;i++){
            ageList.add(i+"");
        }
    }

    private void initEditData() {
        String JsonData = new GetJsonDataUtil().getJson(this, "userInfoAction.json");//获取assets目录下的json文件数据
        //用Gson 转成实体
        editData = JSONUtils.jsonString2Beans(JsonData, EditDataBean.class);
        LogUtils.e(TAG,"initEditData ="+JsonData);
    }

    // 初始化单列的选择器
    private void initOneList() {
        oneListPickerView = new OptionsPickerBuilder(context, (options1, options2, options3, v) -> {
            switch (edit){
                case 0://情感状态
                    married = editData.get(0).getArray().get(options1);
                    tvMarryType.setText(married);
                    break;
                case 2://身高
                    height = editData.get(2).getArray().get(options1);
                    tvHeight.setText(height+"cm");
                    break;
                case 3://体重
                    weight = editData.get(3).getArray().get(options1);
                    tvWeight.setText(weight+"kg");
                    break;
                case 5://收入
                    String income = editData.get(5).getArray().get(options1);
                    income_start = income.split("-")[0];
                    income_end = income.split("-")[1];
                    tvIncome.setText(income);
                    break;
                case 8://是否买车
                    buyCar = editData.get(8).getArray().get(options1);
                    tvBuyCar.setText(buyCar);
                    break;
                case 9://是否买房
                    buyHouse = editData.get(9).getArray().get(options1);
                    tvBuyHouse.setText(buyHouse);
                    break;
                case 10://学历
                    education = editData.get(10).getArray().get(options1);
                    tvEducation.setText(education);
                    break;
                case 11://何时想结婚
                    marryTime = editData.get(11).getArray().get(options1);
                    tvWhenWantMarry.setText(marryTime);
                    break;
                case 99://年龄
                    years = ageList.get(options1);
                    tvAge.setText(years);
                    break;
                case 13://抽烟情况
                    smoke = editData.get(13).getArray().get(options1);
                    tvSmoke.setText(smoke);
                    break;
                case 14://喝酒情况
                    dring = editData.get(14).getArray().get(options1);
                    tvDrink.setText(dring);
                    break;
            }
        }).setLayoutRes(R.layout.pickerview_one_list, v -> {
            TextView tvSubmit = v.findViewById(R.id.tv_finish);
            TextView tvOneContent = v.findViewById(R.id.tv_one_list_content);
            tvSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    oneListPickerView.returnData();
                    oneListPickerView.dismiss();
                }
            });
        }).setOutSideCancelable(true)
                .setTextColorOut(getResources().getColor(R.color.gray9)) // 设置外部区域的色值
                .setDividerColor(getResources().getColor(R.color.white)) // 设置分割线的颜色 不让显示分割线
                .build();
    }

    private void getData() {

        OkGoUtil.getRequets(getContext(), UrlConstants.FIND_FRIEND_CONDITION, null, new JsonCallback<BaseModel<MakeFriendConditionBean>>() {
            @Override
            public void onSuccess(Response<BaseModel<MakeFriendConditionBean>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        setView(response.body().getData());
                    }
                    ToastUtil.showToast(getContext(),response.body().getMsg());
                }
            }

            @Override
            public void onError(Response<BaseModel<MakeFriendConditionBean>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }

    private void setView(MakeFriendConditionBean data) {
        if(data == null){
            return;
        }
        tvCity.setText(data.getLocal_province());
        tvHometown.setText(data.getProvince());
        tvAge.setText(data.getYears());
        tvHeight.setText(data.getHeight()+"cm");
        tvWeight.setText(data.getWeight()+"kg");
        tvEducation.setText(data.getEducation());
        tvIncome.setText(data.getIncome_start()+"-"+data.getIncome_end());
        tvMarryType.setText(data.getMarry_status());
        tvWhenWantMarry.setText(data.getMarry_time());
        tvBuyHouse.setText(data.getIs_house());
        tvBuyCar.setText(data.getIs_car());
        tvSmoke.setText(data.getIs_smoke());
        tvDrink.setText(data.getIs_guzzle());
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return -1;
    }

    @OnClick({R.id.iv_back, R.id.tv_save, R.id.ll_city, R.id.ll_hometown, R.id.ll_age, R.id.ll_height, R.id.ll_weight, R.id.ll_education, R.id.ll_income, R.id.ll_marry_type, R.id.ll_when_want_marry, R.id.ll_buy_house, R.id.ll_buy_car, R.id.ll_smoke, R.id.ll_drink})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_save:
                setMakeFriendCondition();
                break;
            case R.id.ll_city:
                addressType = 1;
                showPickerView();
                break;
            case R.id.ll_hometown:
                addressType = 2;
                showPickerView();
                break;
            case R.id.ll_age:
                edit = 99;
                oneListPickerView.setPicker(ageList);
                oneListPickerView.show();
                break;
            case R.id.ll_height:
                edit = 2;
                oneListPickerView.setPicker(editData.get(2).getArray());
                oneListPickerView.show();
                break;
            case R.id.ll_weight:
                edit = 3;
                oneListPickerView.setPicker(editData.get(3).getArray());
                oneListPickerView.show();
                break;
            case R.id.ll_education:
                edit = 10;
                oneListPickerView.setPicker(editData.get(10).getArray());
                oneListPickerView.show();
                break;
            case R.id.ll_income:
                edit = 5;
                oneListPickerView.setPicker(editData.get(5).getArray());
                oneListPickerView.show();
                break;
            case R.id.ll_marry_type:
                edit = 0;
                oneListPickerView.setPicker(editData.get(0).getArray());
                oneListPickerView.show();
                break;
            case R.id.ll_when_want_marry:
                edit = 11;
                oneListPickerView.setPicker(editData.get(11).getArray());
                oneListPickerView.show();
                break;
            case R.id.ll_buy_house:
                edit = 9;
                oneListPickerView.setPicker(editData.get(9).getArray());
                oneListPickerView.show();
                break;
            case R.id.ll_buy_car:
                edit = 8;
                oneListPickerView.setPicker(editData.get(8).getArray());
                oneListPickerView.show();
                break;
            case R.id.ll_smoke:
                edit = 13;
                oneListPickerView.setPicker(editData.get(13).getArray());
                oneListPickerView.show();
                break;
            case R.id.ll_drink:
                edit = 14;
                oneListPickerView.setPicker(editData.get(14).getArray());
                oneListPickerView.show();
                break;
        }
    }

    private void showPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = mOptions1Items.size() > 0 ?
                        mOptions1Items.get(options1).getPickerViewText() : "";
                String opt2tx = mOptions2Items.size() > 0

                        && mOptions2Items.get(options1).size() > 0 ?

                        mOptions2Items.get(options1).get(options2) : "";
//                String opt3tx = mOptions2Items.size() > 0
//
//                        && mOptions3Items.get(options1).size() > 0
//
//                        && mOptions3Items.get(options1).get(options2).size() > 0 ?
//
//                        mOptions3Items.get(options1).get(options2).get(options3) : "";
                String region = opt1tx + opt2tx;//+ opt3tx
                if(addressType == 1){
                    locationProvince = opt1tx;
                    locationCity = opt2tx;
                    tvCity.setText(region);
                }else{
                    province = opt1tx;
                    city = opt2tx;
                    tvHometown.setText(region);
                }
            }

        }).setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(mOptions1Items, mOptions2Items, null);//三级选择器
        pvOptions.show();
    }

    private void setMakeFriendCondition() {
        Map map = new HashMap();

        if(!StringUtils.isEmpty(locationProvince)){
            map.put("local_province", locationProvince);
        }

        if(!StringUtils.isEmpty(locationCity)){
            map.put("local_city", locationProvince);
        }

        if(!StringUtils.isEmpty(province)){
            map.put("province", province);
        }

        if(!StringUtils.isEmpty(city)){
            map.put("city", city);
        }

        if(!StringUtils.isEmpty(height)){
            map.put("height", height);
        }

        if(!StringUtils.isEmpty(weight)){
            map.put("weight", weight);
        }

        if(!StringUtils.isEmpty(education)){
            map.put("education", education);
        }

        if(!StringUtils.isEmpty(income_start)){
            map.put("income_start", income_start);
        }

        if(!StringUtils.isEmpty(income_end)){
            map.put("income_end", income_end);
        }

        if(!StringUtils.isEmpty(marryTime)){
            map.put("marry_time", marryTime);
        }

        if(!StringUtils.isEmpty(married)){
            map.put("marry_status", married);
        }

        if(!StringUtils.isEmpty(buyCar)){
            map.put("is_car", buyCar);
        }

        if(!StringUtils.isEmpty(buyHouse)){
            map.put("is_house", buyHouse);
        }

        if(!StringUtils.isEmpty(smoke)){
            map.put("is_smoke", smoke);
        }

        if(!StringUtils.isEmpty(dring)){
            map.put("is_guzzle", dring);
        }

        if(!StringUtils.isEmpty(years)){
            map.put("years", years);
        }

        OkGoUtil.postRequest(getContext(), UrlConstants.FIND_FRIEND_CONDITION, map, new JsonCallback<BaseModel<?>>() {
            @Override
            public void onSuccess(Response<BaseModel<?>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        finish();
                    }
                    ToastUtil.showToast(getContext(),response.body().getMsg());
                }
            }

            @Override
            public void onError(Response<BaseModel<?>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }
}